package com.convert.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.convert.Constants.ConvertResult;
import com.convert.domain.ConvertRequest;
import com.convert.domain.ConvertResponse;
import com.convert.util.ExtractUtil;

@Controller
public class ConvertController {

    @Autowired
    private ConvertService convertService;
    
    @RequestMapping(value={"/", "/index"})
    public String index(ConvertRequest request, ModelMap model) {
        
        return "index";
    }
    
    @RequestMapping(value = "/convert", method = RequestMethod.POST)
    public String convert(ConvertRequest request, ModelMap model) {
        
        String param = request.getParam();
        if(StringUtils.isBlank(param)) {
            model.addAttribute("message", ConvertResult.NOT_FOUND_INPUT);
            return "index";
        }
        
        if(!param.contains(ConvertResult.REQUEST_BODY) && !param.contains(ConvertResult.RESPONSE_BODY)) {
            model.addAttribute("message", ConvertResult.NOT_FOUND_BODY);
            return "index";
        }
        
        List<String> sources = ExtractUtil.getSources(request.getParam());
        
        StringBuilder sb = new StringBuilder();
        for(String s : sources) {
            s =  s.replaceAll("(\n\r)+", "");
            sb.append(s).append("\n");
        }
        
        request.setParam(sb.toString());
        
        ConvertResponse result = convertService.convert(sources);
        model.addAttribute("logResponse", result);

        if(result.getNumberOfIncompleteRequestBody() > 0 || result.getNumberOfIncompleteResponseBody() > 0){
        	model.addAttribute("message", ConvertResult.NOT_COMPLETE);
        }
        
        
        return "index";
    }
    
}
